<template>
<div>
  <a-card style="width: 100%">
    <a-form :form="form">
      <a-row>
        <a-col :md="8" :sm="12">
          <a-form-item
            label="开课院系"
            :labelCol="{span: 7,offset: 1}"
            :wrapperCol="{span: 15, offset: 1}"
          >
            <a-select
              v-decorator="['kcyx',
              {
                rules: [{ required: true, message: '请选择开课院系!' }],
                initialValue: kcyx
              }]" @change="yxChange" showSearch :filterOption="filterOption" :disabled="!!editId">
              <a-select-option v-for="i in selectMenu.yxList" :key="i.id" :value="i.dwh">{{ i.dwh }} {{ i.dwmc }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="12">
          <a-form-item
            label="课程名称"
            :labelCol="{span: 7,offset: 1}"
            :wrapperCol="{span: 15, offset: 1}"
          >
            <a-select
              v-decorator="[
                'kcdm',
                {
                  rules: [{ required: true, message: '输入课程名称搜索选择!' }]
                }
              ]"
              showSearch
              :filterOption="filterOption"
              :disabled="!!editId"
              :notFoundContent="null">
              <a-spin v-if="kcLoading" slot="notFoundContent" size="small"/>
              <a-select-option v-for="(i,index) in selectMenu.courseList" :key="index" :value="i.kch">{{ i.kch }}-{{ i.kcmc }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="12">
          <a-form-item
            label="考试年级"
            :labelCol="{span: 7,offset: 1}"
            :wrapperCol="{span: 15, offset: 1}"
          >
            <a-select v-decorator="['ksnj',
              {
                rules: [{ required: true, message: '请选择考试年级!' }],
              }]">
              <a-select-option v-for="i in TYPE0126" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="12">
          <a-form-item
            label="考试学年"
            :labelCol="{span: 7,offset: 1}"
            :wrapperCol="{span: 15, offset: 1}"
          >
            <a-select v-decorator="['ksxn',
              {
                rules: [{ required: true, message: '请选择考试学年!' }],
              }]">
              <a-select-option v-for="i in TYPE0125" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="12">
          <a-form-item
            label="考试学期"
            :labelCol="{span: 7,offset: 1}"
            :wrapperCol="{span: 15, offset: 1}"
          >
            <a-select v-decorator="['ksxq',
              {
                rules: [{ required: true, message: '请选择考试学期!' }],
              }]">
              <a-select-option v-for="i in TYPE0072" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="12">
          <a-form-item
            label="考试性质"
            :labelCol="{span: 7,offset: 1}"
            :wrapperCol="{span: 15, offset: 1}"
          >
            <a-select v-decorator="['ksxz',
              {
                rules: [{ required: true, message: '请选择考试性质!' }],
              }]">
              <a-select-option v-for="i in TYPE0358 && TYPE0358.filter(item => item.name !== '补考')" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="12">
          <a-form-item
            label="考试类别"
            :labelCol="{span: 7,offset: 1}"
            :wrapperCol="{span: 15, offset: 1}"
          >
            <a-select v-decorator="['kslb',
              {
                rules: [{ required: true, message: '请选择考试类别!' }],
                initialValue: '1'
              }]">
              <a-select-option v-for="i in TYPE0109" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="12">
          <a-form-item
            label="成绩类型"
            :labelCol="{span: 7,offset: 1}"
            :wrapperCol="{span: 15, offset: 1}"
          >
            <a-select v-decorator="['cjlx',
              {
                rules: [{ required: true, message: '请选择成绩类型!' }],
                initialValue: '01'
              }]">
              <a-select-option v-for="i in TYPE0328" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="12">
          <a-form-item
            label="考试时间"
            :labelCol="{span: 7,offset: 1}"
            :wrapperCol="{span: 15, offset: 1}"
          >
            <a-date-picker v-decorator="['ksrq',
              {
                rules: [{ required: true, message: '请选择考试时间!' }],
              }]"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="12">
          <a-button style="margin-left: 10px;" type="primary" @click="startAdd" :disabled="hasErrors(form.getFieldsError())">开始录入成绩</a-button>
          <a-button style="margin-left: 10px;" type="primary" @click="exportEcl" :disabled="hasErrors(form.getFieldsError())" v-if="personal">导出</a-button>
          <a-button style="margin-left: 10px;" type="primary" @click="exportExam" :disabled="hasErrors(form.getFieldsError())" v-if="personal">下载成绩模版</a-button>
          <!-- <a-button type="primary" @click="$refs.table.refresh(true)" v-if="personal" style="margin:0 10px">查询</a-button> -->
        </a-col>
        <a-col :md="12" :sm="12" style="text-align:right" v-if="personal">
        <div>
            <a-upload
              :fileList="fileList"
              :remove="handleRemove"
              :beforeUpload="beforeUpload"
            >
              <a-button type="primary" :disabled="hasErrors(form.getFieldsError())" >选择文件</a-button>
              <a-button
                type="primary"
                @click.stop="handleImport"
                :disabled="fileList.length === 0"
                :loading="uploading"
              >
                {{uploading ? 'Uploading' : '导入' }}
              </a-button>
            </a-upload>
          </div>
          </a-col>
      </a-row>
    </a-form>
    <add-modal
      ref="add"
      :visible="visible"
      :TYPE0519="TYPE0519"
      :modelForm = modelForm
      @cancel="visible = false"
      @refresh="$refs.table.refresh(false)"
    />
    <cj-upload
      ref="upload"
      :cjVisible="cjVisible"
      :uploadList="uploadList"
      @cjCancel="cjVisible = false"
      :loading="loading"
      @submitCheck="submitCheck"
      @refresh="$refs.table.refresh(false)"
    />
  </a-card>
  <a-card v-if="personal" :bordered="false" style="margin-top: 10px">
      <s-table
        ref="table"
        size="default"
        rowKey="index"
        :columns="columns"
        :data="loadData"
        :alert="{show: false}"
        :pagination="{ pageSize: 10 }"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>

        <template slot="operation" slot-scope="text, record">
          <a  @click="editThis(record,true)">详情</a>
          <a v-if="record.cjztm == '01' || record.cjztm == '04' || record.cjztm == '06'" @click="editThis(record,false)">修改</a>
           <a v-if="record.cjztm == '01' || record.cjztm == '04' || record.cjztm == '06'"  @click="submit(record.id)">提交</a>

        </template>
      </s-table>
    </a-card>
</div>
</template>

<script>
import { mapState } from 'vuex'
import { DateToString } from '@/utils/common'
import addModal from './addModal'
import cjUpload from './cjUpload'
import { STable } from '~'
let timeout;
let currentValue;
function hasErrors(fieldsError) {
  return Object.keys(fieldsError).some(field => fieldsError[field]);
}
export default {
  data () {
    return {
      loading: false,
      hasErrors,
      uploadList: [],
      fileList: [],
      uploading: false,
      form: this.$form.createForm(this),
      selectMenu: {},
      kcLoading: false,
      editId: null,
      visible: false,
      cjVisible:false,
      submitObj: {},
      kcyx: null,
      kcdm: null,
      formData:{},
      url:process.env.SERVICE_URL,
      personal:false,
      queryParam: {},
      modelForm:{},
      columns: [
//         {
//           title: this.$t('key.no'),
//           scopedSlots: { customRender: 'serial' }
//         },
        {
          title: '用户名',
          dataIndex: 'lrdsxm',
          width: 120,
        },
        {
          title: '用户编号',
          dataIndex: 'lrds',
          width: 150,
        },
        {
          title: '开课院系',
          dataIndex: 'ksyxmc'
        },
        {
          title: "课程名称",
          dataIndex: 'kcmc'
        },
        {
          title: '考试年级',
          dataIndex: 'ksnj'
        },
        {
          title: '考试学年',
          dataIndex: 'ksxn'
        },
        {
          title: '考试学期',
          dataIndex: 'ksxqmc'
        },
        {
          title: '考试日期',
          dataIndex: 'ksrq'
        },
        {
          title: '更新时间',
          dataIndex: 'updateDate'
        },
        {
          title: '状态',
          dataIndex: 'cjztmc',

        },
        {
          title: '操作',
          width: '160px',
          dataIndex: 'id',
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      loadData: parameter => {
        parameter.pageNum = parameter.pageNo
        let params = Object.assign(this.queryParam, parameter)
        return this.$api.cultivate.ycjruList(params).then(res => {
            res.data.rows.map(item =>{
                if(item.cfsj)item.cfsj=moment(item.cfsj).format('YYYY-MM-DD')
            })
          return {
            data: res.data.rows ? res.data.rows : [],
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize,
            totalPage: Math.ceil(res.data.total / parameter.pageSize),
            totalCount: res.data.total
          }
        })
      },
    }
  },
  components: {addModal,STable,cjUpload},
  computed: {
    ...mapState({
      TYPE0125: state => state.app['TYPE0125'],
      TYPE0126: state => state.app['TYPE0126'],
      TYPE0072: state => state.app['TYPE0072'],
      TYPE0358: state => state.app['TYPE0358'],
      TYPE0109: state => state.app['TYPE0109'],
      TYPE0328: state => state.app['TYPE0328'],
      TYPE0519: state => state.app['TYPE0519'],
    })
  },
    mounted() {
    this.$nextTick(() => {
      // To disabled submit button at the beginning.
      this.form.validateFields();
    });
  },
  activated(){
    // this.personal=this.$route.name === '单科成绩录入'?true:false
    // console.log(this.$route.name)
    this.$api.cultivate.scoreAddStuCheckManage().then(res => {
          console.log(res)
          if(!res.data){
            this.$store.dispatch('app/sysInfo', true).then(data => {
              console.log(data)
              if ( +new Date() > +data.cjlrjssj  ||  +new Date() < +data.cjlrkssj) {
                this.$confirm({
                  title: '当前不在成绩录入时间范围，无法进行操作',
                  centered: true,
                  okText: '确认',
                  cancelText: '返回',
                  onOk: () => {
                    this.$router.back()
                  },
                  onCancel: () => {
                    this.$router.back()
                  }
                })
              }
            })
          }
        }).finally(() => {
          // this.kcLoading = false
    })


  },
  watch:{
      '$route'( to , from ){
      this.personal=to.name === '单科成绩录入'?true:false
      }
  },
  created () {
    this.personal=this.$route.name === '单科成绩录入'?true:false
    console.log(this.$route.name)
    this.$store.dispatch('app/setDictionary', 'TYPE0125')
    this.$store.dispatch('app/setDictionary', 'TYPE0126')
    this.$store.dispatch('app/setDictionary', 'TYPE0072')
    this.$store.dispatch('app/setDictionary', 'TYPE0358')
    this.$store.dispatch('app/setDictionary', 'TYPE0109')
    this.$store.dispatch('app/setDictionary', 'TYPE0328')
    this.$store.dispatch('app/setDictionary', 'TYPE0519')
    this.initSelectMenu()
  },
  methods: {
    submit(id){
      this.$api.cultivate.dkcjtj({id}).then(res => {
          this.$message.success(res.msg || '提交成功')
          console.log(res)
          this.$refs.table.refresh(true)
      })

    },
    editThis(item,bool){
      this.$api.cultivate.cjruList({id:item.id}).then(res => {
          console.log(res)
          this.modelForm = {
            kcyx: item.ksyxm,
            kcdm: item.kcbm,
            ksnj: item.ksnj,
            ksxn: item.ksxn,
            ksxq: item.ksxqm,
            ksxz: item.ksxzm,
            kslb: item.kslbm,
            cjlx: item.cjlxm,
            ksrq: item.ksrq,
          }
          this.$refs.add.isEdit = bool
          this.$refs.add.id = item.id
          this.visible = true
          this.$refs.add.cjksxsmdList = typeof res.data === 'object' ? res.data : []
          this.$refs.add.params = this.modelForm
      })
    },
    initSelectMenu () {
      let allRequest = [
        this.$api.base.collegeAll(),
        this.$store.dispatch('app/sysInfo')
      ]
      Promise.all(allRequest).then(res => {
        this.selectMenu = {
          yxList: res[0].data
        }
        this.form.setFieldsValue({
          kcyx: res[0].data[0].dwh,
          ksnj: res[1].currentGrade,
          ksxq: res[1].currentSemester,
          ksxn: res[1].schoolYear,
          cjlx: '01'
        })
        this.yxChange(res[0].data[0].dwh)
      })

    },
    filterOption (value, op) {
      return op.componentOptions.children[0].text.indexOf(value) !== -1
    },
    yxChange (code) {
      console.log(code)
      this.form.setFieldsValue({kcbm: ''})
      this.$set(this.selectMenu, 'courseList', [])
      if (code) {
        this.kcLoading = true
        this.$api.cultivate.selectList4AddCourse({kcssyxm: code}).then(res => {
          this.$set(this.selectMenu, 'courseList', res.data)
        }).finally(() => {
          this.kcLoading = false
        })
      } else {
        this.$set(this.selectMenu, 'courseList', [])
      }
      // const self = this
      // setTimeout(()=>{
      //   self.form.setFieldsValue({kcdm: ''})
      //   self.$set(this.selectMenu, 'courseList', [])
      // },0)
    },
    // FIXME 课程选择
    fetch(value){
      const code =  this.form.getFieldValue('kcyx')
      if (code && value && value.length) {
        this.kcLoading = true
        this.$api.cultivate.courseAll({kcssyxm: code, kcmc: value}).then(res => {
          this.$set(this.selectMenu, 'courseList', res.data)
        }).finally(() => {
          this.kcLoading = false
        })
      } else {
        this.$set(this.selectMenu, 'courseList', [])
      }
    },
    handleSearch (value) {
      console.dir(value)
      this.fetch(value)
    },
    kcChange (kch) {
      // console.dir(kch)
      // let kc = this.selectMenu.courseList.find(kc => {
      //   return kc.kch === kch
      // })
      // // this.form.setFieldsValue({
      // //   xf: kc.xf
      // // })
      // this.fetch(kc.kcmc)
    },
    startAdd () {
      this.form.validateFields((err, values) => {
        if (err) {
          return
        }
        // let params = {
        //   kcyx: '021',
        //   kcdm: '215600302',
        //   ksnj: '2017',
        //   ksxn: '2017-2018',
        //   ksxq: '2',
        //   kslb: 1,
        //   ksxz: '01',
        //   ksrq: '2019-09-11'
        // }
        this.$refs.add.isEdit = false
        DateToString(values)
        let apiFn = this.$route.name === '单科成绩录入' ? 'scoreAddStuList' : 'scoreAddStuCheck'
        this.$api.cultivate[apiFn](values).then(res => {
          this.visible = true
          this.modelForm = values
          this.$refs.add.cjksxsmdList = typeof res.data === 'object' ? res.data : []
          const noteArr = this.TYPE0519.map(note => note.name)
          this.$refs.add.cjksxsmdList.forEach(xs => {
            if (!noteArr.includes(xs.note)) {
              xs.note = ''
            }
          })
          if (values.cjlx === '03') { // 免修类型 成绩显示免修
            this.$refs.add.cjksxsmdList.forEach(c => c.kscj = '免修')
          }
          this.$refs.add.params = values
        })
        // DateToString(values)
        // this.$api.cultivate.scoreAddStuList(values)
      })
      // let params = {
      //   kcyx: '021',
      //   kcdm: '215600302',
      //   ksnj: '2017',
      //   ksxn: '2017-2018',
      //   ksxq: '2',
      //   kslb: 1,
      //   ksxz: '01',
      //   ksrq: '2019-09-11'
      // }
    },
    exportEcl(){
      //  var d = new Date(this.form.getFieldsValue().ksrq);
      //   var datetime=d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
      //  this.form.setFieldsValue({'ksrq':datetime})
       this.form.validateFields((err, values) => {
        if (err) {
          return
        }
        DateToString(values)
        this.$export('foster/kccj/exportExcel',values)
        })
    },
    exportExam(){
      this.form.validateFields((err, values) => {
        if (err) {
          return
        }
        DateToString(values)
        this.$export('foster/kccj/exportExcelMb',values)
        })
    },
  handleRemove (file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    beforeUpload (file) {
      this.fileList = [...this.fileList, file]
      return false
    },
    // 导入
    handleImport () {
      this.form.validateFields((err, values) => {
        if (err) {
          return
        }
      const { fileList } = this
      const formData = new FormData()
      fileList.forEach((file) => {
        formData.append('file', file)
      })
      console.log('formData:',formData)
      console.log('fileList:',fileList)
      this.uploading = true
      this.$upload('foster/kccj/drdkcjUpload',formData).then( res => {
        this.cjVisible = true
        this.uploadList = res.data
        this.uploading = false
        let params = res.data
        for(let i=0;i<params.length;i++){
          params[i].cjlxm=this.form.getFieldsValue().cjlx
          params[i].xsxh = params[i].xh
        }
        DateToString(values)
          this.submitObj={
            cjlx: values.cjlx,
            kcdm: values.kcdm,
            kcyx: values.kcyx,
            kslb: values.kslb,
            ksnj: values.ksnj,
            ksrq: values.ksrq,
            ksxn: values.ksxn,
            ksxq: values.ksxq,
            ksxz: values.ksxz,
            cjksxsmdList: params,
            shzt: '02',
            sftj: true,
          }

      }).finally( res => {
          this.uploading = false
        })

       })
      console.log('开始导入')
    },

    submitCheck(data){
      console.log(data)
      // this.$api.cultivate.scoreSubAdd(this.submitObj).then(res => {
      //     console.log(res)
      //     this.loading = false
      //     this.cjVisible = false
      //     this.$message.success(`已成功录入${data}人`)
      //     this.$refs.table.refresh(true)
      // }).finally(() => {
      //     this.loading = false
      //   })
      console.log(this.submitObj)
      this.$postToDow('/foster/kccj/dkcjlrAdd',this.submitObj).then( res => {
        console.log(res)
          this.loading = false
          this.cjVisible = false
          this.$message.success(`已成功录入${data}人`)
          this.$refs.table.refresh(true)
      }).finally(res=>{
        this.loading = false
      })
    }
  }
}
</script>

<style lang="less" scoped>
  /deep/ .ant-upload-list-item-name{
    padding: 0 30px
  }
</style>
